package com.mylearn.myblog.service.impl;

import com.mylearn.myblog.dao.TagRepository;
import com.mylearn.myblog.entity.Tag;
import com.mylearn.myblog.service.TagService;
import javassist.NotFoundException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TagServiceImpl implements TagService {

	@Autowired
	private TagRepository tagRepository;

	@Transactional
	@Override
	public Tag saveTag(Tag tag) {
		return tagRepository.save(tag);
	}

	@Transactional
	@Override
	public Tag getTag(Long id) {
		return tagRepository.getOne(id);
	}

	@Transactional
	@Override
	public Tag getTagByName(String name) {
		return tagRepository.findByName(name);
	}

	@Transactional
	@Override
	public Page<Tag> listTag(Pageable pageable) {
		return tagRepository.findAll(pageable);
	}

	@Transactional
	@Override
	public Tag updateTag(Long id, Tag tag) {
		Tag tag1 = tagRepository.getOne(id);
		if (tag1 == null){
			try {
				throw new NotFoundException("Id 不存在");
			} catch (NotFoundException e) {
				e.printStackTrace();
			}
		}
		BeanUtils.copyProperties(tag,tag1);
		tag1.setId(id);
		return tagRepository.saveAndFlush(tag1);
	}

	@Transactional
	@Override
	public void deleteTag(Long id) {
		tagRepository.deleteById(id);
	}

	@Override
	public List<Tag> listAll() {
		return tagRepository.findAll();
	}
}
